"use strict";
let isInit = false;
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const cfg = require("./config/database");
const initMongoose = function() {
	mongoose.connection.on("error", err => console.error("mongodb连接错误", err));
	mongoose.connection.on("connecting", () => console.log("正在连接mongodb"));
	mongoose.connection.on("connected", () => console.warn("mongodb 连接成功"));
	mongoose.connection.on("disconnected", () => console.warn("mongodb 失去连接，注意此时所有请求数据库的请求都被mogoose缓存了，因此看不到有请求进去的，因为么个请求都要经过session比较"));
	mongoose.connection.on("reconnected", () => console.warn("mongodb 重新连接成功"));
	mongoose.connection.once("open", () => () => console.warn("mongodb 打开"));
	if (!cfg.isCluster) {
		mongoose.connect(cfg.single.url, cfg.single.options);
	} else {
		mongoose.connect(cfg.replica.url, cfg.replica.options);
	}

	/*
	这里不能用createConnection然后再connection.open来执行啊，因为mongoose.connection是默认的连接，
	而mongoose.createConnection()会创建一个新的连接，这个两个不是一回事
	const db = mongoose.createConnection();
	mongoose.connection === db，这里会返回一个false表明连接是不一样的
	*/
};
const loadModel = function() { //注意所有的model都是基于mogoose的默认连接，即mongoose.connection创建的，一个model对应一个connection
	require("./models/suite_model");
	require("./models/suite_to_org_model");
};
const init = function() {
	if (!isInit) {
		loadModel();
		initMongoose();
		isInit = true;
	}
};
module.exports = {
	init,
	mongoose
};
